layui.use(['admin', 'form', 'upload'], function() {
	let $ = layui.$,
		admin = layui.admin,
		setter = layui.setter,
		form = layui.form,
		upload = layui.upload;

	setTimeout(function() {
		let token = layui.data(setter.tableName)[setter.request.tokenName];
		let tokenName = setter.request.tokenName;
		let uploadInst = upload.render({
		    elem: '#manage-data-upload-normal'
		    ,url: setter.request.domainName + '/admin/Ajax/upload?server=true&' + tokenName + '=' + token
		    ,accept: 'images'
		    ,acceptMime: 'image/jpeg,image/png,image/jpg'
		    ,exts: 'jpeg|jpg|png'
		    ,size: setter.maxFileSize * 1024
		    ,before: function(obj){
		        // 预读本地文件示例，不支持ie8
		        // obj.preview(function(index, file, result){
		        //     $('#upload-normal-img').attr('src', result); //图片链接（base64）
		        // });
		    }
		    ,done: function(res){
		        //如果上传失败
		        if(res.code === 1){
		            let full_url = res.data.file.full_url;
		            let url = res.data.file.url;
		            $('#manage-data-upload-normal-img').attr('src', full_url);
		            form.val("managePopup", {
		                "img": url,
		            });
		            return layer.msg('上传成功！');
		        }else{
		            return layer.msg('上传失败！');
		        }
		        //上传成功
		    }
		    ,error: function(){
		        //演示失败状态，并实现重传
		        // uploadInst.upload(); // 重新上传
		    }
		});
		$(document).on('click', '.img-show', function (e) {
		    let src = $(this).attr("src");
		    layer.photos({
		        photos: {
		            "title": "Photos",
		            "start": 0,
		            "data": [
		                {
		                    "alt": "",
		                    "pid": 1,
		                    "src": src,
		                }
		            ]
		        },
		        footer: false // 是否显示底部栏 --- 2.8.16+
		    });
		});
		getOrderData();
	}, 500);
	
	setTimeout(function() {
		getCommodity();
	}, 700);
	
	setTimeout(function() {
		getShopData();
	}, 800);

	let layerIndex = '';
	layui.data.sendParams = function(params) {
		layerIndex = params.lay_index;
	}
	// 新增
	form.on('submit(laySubmitAdd)', function(data) {
		let field = data.field; //获取提交的字段
		// 提交 Ajax 成功后，关闭当前弹层并重载表格
		admin.req({
			url: setter.request.domainName + '/admin/manageData.index/add' //实际使用请改成服务端真实接口
			, data: field
			, type: 'POST'
			, loading: true // 是否开启加载框
			, done: function(res) {
				admin.message({
					title: '提交成功',
					offset: '15px',
					icon: 1,
					time: 1500
				})
				layui.table.reload('manageDataTable'); //重载表格
				layer.close(layerIndex); //执行关闭
			}
		})
	});
	// 开启提交
	form.on('submit(laySubmitEdit)', function(data) {
		let field = data.field; //获取提交的字段
		admin.req({
			url: setter.request.domainName + '/admin/manageData.index/edit'
			, data: field
			, type: 'POST'
			, loading: true // 是否开启加载框
			, done: function(res) {
				admin.message({
					title: '提交成功',
					offset: '15px',
					icon: 1,
					time: 1500
				})
				layui.table.reload('manageDataTable'); //重载表格
				layer.close(layerIndex); //执行关闭
			}
		});
	});

	let field1 = {
		isTree: false,
		absoluteAuth: true, //
		initKey: '', // 初始key名称
		initValue: '', // 初始值
		select: true,
		quick_search: '',
		action: "index"
	};
	/**
	 * 获取订单数据
	 * @param {Object} n
	 */
	window.getOrderData = function() {
		admin.req({
			url: setter.request.domainName + '/admin/order.index/index'
			, data: field1
			, type: 'get'
			, loading: true // 是否开启加载框
			, is_message: false
			, done: function(res) {
				let selectData = [];
				let initData = [];
				let arrNodE = $("#order_id");
				let ids = arrNodE.val();
				if (res.data.options) {
					selectData = res.data.options;
				}
				if(ids !== 0 && ids !== '0' && ids){
					// 编辑选中
					initData = ids.split(",");
				}
				initXmSelect("#commOrderPopupXmSelect", selectData, initData);
			}
		})
	}

	/**
	 * 获取商品数据
	 * @param {Object} n
	 */
	window.getCommodity = function() {
		admin.req({
			url: setter.request.domainName + '/admin/commodity.index/index'
			, data: field1
			, type: 'get'
			, loading: true // 是否开启加载框
			, is_message: false
			, done: function(res) {
				let selectData = [];
				let initData = [];
				let arrNodE = $("#commodity_id");
				let ids = arrNodE.val();
				if (res.data.options) {
					selectData = res.data.options;
				}
				if(ids !== 0 && ids !== '0' && ids){
					// 编辑选中
					initData = ids.split(",");
				}
				initXmSelect("#commDataPopupXmSelect", selectData, initData);
			}
		})
	}

	/**
	 * 获取店铺数据
	 * @param {Object} n
	 */
	window.getShopData = function() {
		admin.req({
			url: setter.request.domainName + '/admin/shop.index/index'
			, data: field1
			, type: 'get'
			, loading: true // 是否开启加载框
			, is_message: false
			, done: function(res) {
				let selectData = [];
				let initData = [];
				let arrNodE = $("#shop_id");
				let ids = arrNodE.val();
				if (res.data.options) {
					selectData = res.data.options;
				}
				if(ids !== 0 && ids !== '0' && ids){
					// 编辑选中
					initData = ids.split(",");
				}
				initXmSelect("#commShopPopupXmSelect", selectData, initData);
			}
		})
	}

	/**
	 * 初始化xmSelect
	 * @param {Object} n
	 */
	window.initXmSelect = function(node = '', optionData = [], initData = []) {
		return xmSelect.render({
			el: node,
			prop: {
				name: 'name',
				value: 'id',
			},
			language: 'zn',
			autoRow: true, // 自动换行
			filterable: true, // 开启搜索模式
			paging: true, // 开启分页
			pageSize: 50, // 每页显示条数
			initValue: initData, // 默认选中
			radio: true, // 开启单选
			clickClose: true, // 单选完关闭下拉
			toolbar: {
				show: true, // 显示工具条
				list: ['ALL', 'CLEAR', 'REVERSE'], // 全选、清空、反选
			},
			template({ item, sels, name, value }){
				if(node === '#commOrderPopupXmSelect'){
					nodeStr = "order_id";
					return item.name + '(' + item.shop_name + ')';
				}
				return item.name; 
			},
			data: optionData,
			on: function(data) {
				// change, 此次选择变化的数据,数组
				let arr = data.arr;
				let nodeStr = '';
				let id = 0;
				if(node === '#commOrderPopupXmSelect'){
					nodeStr = "order_id";
				}else if(node === '#commShopPopupXmSelect'){
					nodeStr = "shop_id";
				}else if(node === '#commDataPopupXmSelect'){
					nodeStr = "commodity_id";
				}
				if(arr.length > 0){
					id = arr[0]['id'];
				}
				$("#" + nodeStr).val(id);
			}
		});
	}
})